package com.itheima.controller.backend.security;

import com.itheima.common.constant.MessageConstant;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Encounter
 */
@Service
public class SpringSecurityUserService implements UserDetailsService
    {
        //查找服务，实现查询数据库
        @Autowired
        private UserService userService;
        
        /**
         * 根据用户名查询数据库中用户信息
         *
         * @param username 用户名
         * @return {@link UserDetails }
         * @throws UsernameNotFoundException 用户名不发现异常
         */
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
            {
                User user = userService.loadUserByUsername(username);
                if (user == null)
                    {
                        throw new UsernameNotFoundException(MessageConstant.GET_USERNAME_FAIL);
                    }
                
                //获取用户权限
                List<String> list = userService.getAuthList(username);
                ArrayList<GrantedAuthority> auths = new ArrayList<>();
                list.forEach(obj -> auths.add(new SimpleGrantedAuthority(obj)));
                return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), auths);
            }
    }

